package com.cwz.log.aspect;

import com.alibaba.fastjson2.JSON;
import com.cwz.api.entity.SysOperLog;
import com.cwz.core.utils.ip.IpUtils;
import com.cwz.core.utils.servle.ServletUtils;
import com.cwz.core.utils.string.StringUtils;
import com.cwz.log.annotation.Log;
import com.cwz.log.enums.BusinessStatus;
import com.cwz.log.filter.PropertyPreExcludeFilter;
import com.cwz.log.service.AsyncLogService;
import com.cwz.security.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collection;
import java.util.Map;

/**
 * @program: w-demo
 * @description: 操作日志记录切面处理
 * @author: Wen
 **/
@Aspect
@Component
@Slf4j
public class LogAspect {
	@Autowired
	private AsyncLogService asyncLogService;

	/** 排除敏感属性字段 */
	private static final String[] EXCLUDE_PROPERTIES = { "password", "oldPassword", "newPassword", "confirmPassword" };

	/**
	 * @Description: 处理完请求后执行
	 * @Author: Wen
	 * @param joinPoint:
	 * @param controllerLog:
	 * @param jsonResult:
	 * @return: void
	 **/
	@AfterReturning(pointcut = "@annotation(controllerLog)", returning = "jsonResult")
	public void doAfterReturning(JoinPoint joinPoint, Log controllerLog, Object jsonResult) {
		handleLog(joinPoint, controllerLog, null, jsonResult);
	}

	/**
	 * @Description: 拦截异常操作
	 * @Author: Wen
	 * @param joinPoint:
	 * @param controllerLog:
	 * @param e:
	 * @return: void
	 **/
	@AfterThrowing(pointcut = "@annotation(controllerLog)", throwing = "e")
	public void doAfterThrowing(JoinPoint joinPoint, Log controllerLog, Exception e) {
		handleLog(joinPoint, controllerLog, e, null);
	}

	/**
	 * @Description: 日志处理
	 * @Author: Wen
	 * @param joinPoint:
	 * @param controllerLog:
	 * @param e:
	 * @param jsonResult:
	 * @return: void
	 **/
	private void handleLog(final JoinPoint joinPoint, Log controllerLog, final Exception e, Object jsonResult) {
		try {
			// *========数据库日志=========*//
			SysOperLog sysOperLog = new SysOperLog();
			sysOperLog.setStatus(BusinessStatus.SUCCESS.ordinal());
			sysOperLog.setOperIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
			sysOperLog.setOperUrl(StringUtils.substring(ServletUtils.getRequest().getRequestURI(), 0, 255));
			String username = SecurityUtils.getUsername();
			if (StringUtils.isNotBlank(username)) {
				sysOperLog.setOperName(username);
			}
			if (e != null) {
				sysOperLog.setStatus(BusinessStatus.FAIL.ordinal());
				sysOperLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
			}
			// 设置方法名称
			String className = joinPoint.getTarget().getClass().getName();
			String methodName = joinPoint.getSignature().getName();
			sysOperLog.setMethod(className + "." + methodName + "()");
			// 设置请求方式
			sysOperLog.setRequestMethod(ServletUtils.getRequest().getMethod());
			// 处理设置注解上的参数
			getControllerMethodDescription(joinPoint, controllerLog, sysOperLog, jsonResult);
			// 保存数据库
			this.asyncLogService.saveSysLog(sysOperLog);
		} catch (Exception exp) {
			// 记录本地异常日志
			log.error("异常信息:{}", exp.getMessage());
			exp.printStackTrace();
		}
	}

	/**
	 * @Description: 获取注解中对方法的描述信息 用于 Controller 层注解
	 * @Author: Wen
	 * @param joinPoint:
	 * @param log:
	 * @param sysOperLog:
	 * @param jsonResult:
	 * @return: void
	 **/
	private void getControllerMethodDescription(JoinPoint joinPoint, Log log, SysOperLog sysOperLog, Object jsonResult) throws Exception {
		// 设置业务类型
		sysOperLog.setBusinessType(log.businessType().ordinal());
		// 设置模块名称
		sysOperLog.setTitle(log.title());
		// 设置操作人类别
		sysOperLog.setOperatorType(log.operatorType().ordinal());
		// 是否需要保存request，参数和值
		if (log.isSaveRequestData()) {
			// 获取参数的信息，传入到数据库中
			setRequestValue(joinPoint, sysOperLog);
		}
		// 是否需要保存response，参数和值
		if (log.isSaveResponseData() && StringUtils.isNotNull(jsonResult)) {
			sysOperLog.setJsonResult(StringUtils.substring(JSON.toJSONString(jsonResult), 0, 2000));
		}
	}

	/**
	 * @Description: 获取请求的参数，放到 log 中
	 * @Author: Wen
	 * @param joinPoint:
	 * @param sysOperLog:
	 * @return: void
	 **/
	private void setRequestValue(JoinPoint joinPoint, SysOperLog sysOperLog) throws Exception {
		String requestMethod = sysOperLog.getRequestMethod();
		if (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod)) {
			String params = argsArrayToString(joinPoint.getArgs());
			sysOperLog.setOperParam(StringUtils.substring(params, 0, 2000));
		} else {
			Map<?, ?> paramsMap = ServletUtils.getParamMap(ServletUtils.getRequest());
			sysOperLog.setOperParam(StringUtils.substring(JSON.toJSONString(paramsMap, excludePropertyPreFilter()), 0, 2000));
		}
	}

	/**
	 * @Description: 参数拼装
	 * @Author: Wen
	 * @param paramsArray:
	 * @return: java.lang.String
	 **/
	private String argsArrayToString(Object[] paramsArray) {
		String params = "";
		if (paramsArray != null && paramsArray.length > 0) {
			for (Object o : paramsArray) {
				if (StringUtils.isNotNull(o) && !isFilterObject(o)) {
					try {
						String jsonObj = JSON.toJSONString(o, excludePropertyPreFilter());
						params += jsonObj.toString() + " ";
					} catch (Exception e) {
					}
				}
			}
		}
		return params.trim();
	}

	/**
	 * @Description: 忽略敏感属性
	 * @Author: Wen
	 * @return: com.cwz.log.filter.PropertyPreExcludeFilter
	 **/
	private PropertyPreExcludeFilter excludePropertyPreFilter() {
		return new PropertyPreExcludeFilter().addExcludes(EXCLUDE_PROPERTIES);
	}

	/**
	 * @Description: 判断是否需要过滤的对象
	 * @Author: Wen
	 * @param o:  	对象信息
	 * @return: boolean
	 * 如果是需要过滤的对象，则返回true；否则返回false
	 **/
	@SuppressWarnings("rawtypes")
	private boolean isFilterObject(final Object o) {
		Class<?> clazz = o.getClass();
		if (clazz.isArray()) {
			// isAssignableFrom() 它的作用是用来判断两个类的之间的关联关系，也可以说是一个类是否可以被强制转换为另外一个实例对象
			return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
		} else if (Collection.class.isAssignableFrom(clazz)) {
			Collection collection = (Collection) o;
			for (Object value : collection) {
				return value instanceof MultipartFile;
			}
		} else if (Map.class.isAssignableFrom(clazz)) {
			Map map = (Map) o;
			for (Object value : map.entrySet()) {
				Map.Entry entry = (Map.Entry) value;
				return entry.getValue() instanceof MultipartFile;
			}
		}
		return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse
			|| o instanceof BindingResult;
	}
}
